﻿namespace Common.Interfaces

{
    /// <summary>
    /// 值对象基类 重写相等验证
    /// </summary>
    public abstract class ValueObject : IEquatable<ValueObject>
    {
        /// <summary>
        /// 获取需要比较的内容
        /// </summary>
        /// <returns></returns>
        protected abstract IEnumerable<object> GetEqualityComponents();

        #region 相等验证 包含重写的== !=
        public override bool Equals(object? obj)
            => obj is ValueObject other && Equals(other);

        public bool Equals(ValueObject? other)
            => other is not null && GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());

        public override int GetHashCode()
            => GetEqualityComponents()
                .Aggregate(17, (hash, obj) => hash * 23 + (obj?.GetHashCode() ?? 0));

        public static bool operator ==(ValueObject? left, ValueObject? right)
            => Equals(left, right);

        public static bool operator !=(ValueObject? left, ValueObject? right)
            => !Equals(left, right);
        #endregion
    }
}
